import os
import json
from datetime import datetime
import pytest

if __name__ == '__main__':
    # 1. 统一放在 allure-results/logs 下
    allure_results = "./report/allure-results"
    os.makedirs(f"{allure_results}/logs", exist_ok=True)

    timestamp   = datetime.now().strftime("%Y%m%d_%H%M%S")
    log_file    = f"./logs/test_{timestamp}.log"

    # 2. 跑用例
    pytest.main([
        "./tests/ui/test_login.py",
        "-s",
        f"--alluredir={allure_results}",
        f"--override-ini=log_file={log_file}"
    ])

    # 3. 生成 attachment 描述，让 Allure 把日志当成附件显示
    attach_desc = {
        "name": f"测试日志 ({os.path.basename(log_file)})",
        "type": "text/plain",
        "source": f"logs/{os.path.basename(log_file)}"   # 相对于 allure-results 的路径
    }
    with open(f"{allure_results}/logs-attachment.json", "w", encoding="utf-8") as f:
        json.dump(attach_desc, f, ensure_ascii=False, indent=2)

    # 4. 生成最终 HTML 报告
    os.system(f"allure generate {allure_results} -o ./report/allure-report --clean")
    print("\n报告已生成，浏览器打开: allure open ./report/allure-report")